package com.chain.BrotherExchange.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.event.SubmitAlipayEvent;
import com.chain.BrotherExchange.event.SubmitWeChatPayEvent;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.ui.dialog.SendVerificationCodeDialog;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.utils.TimeCount;
import com.chain.BrotherExchange.viewmodel.PaymentViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.Bind;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 添加微信支付或支付宝
 */
public class AddWeChatPayOrAliPayActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @Bind(R.id.apply_button) Button mApplyButton;
    @Bind(R.id.name_edit) EditText mNameEditText;
    @Bind(R.id.payment_text) TextView paymentText;
    @Bind(R.id.payment_image) ImageView paymentImage;
    @Bind(R.id.pay_account_text) TextView payAccountText;
    @Bind(R.id.pay_account_edit) EditText payAccountEdit;
    @Bind(R.id.add_image_hint_layout) View mAddImageHintLayout;
    @Bind(R.id.receipt_qr_code_image) ImageView mReceiptQrCodeImage;
    @Bind(R.id.select_receipt_qr_code_layout) View mSelectReceiptQrCodeLayout;

    private int mPageType;
    private Uri mReceiptQrCodeUri; // 支付方式 uri
    private PaymentViewModel mPaymentViewModel;

    public static void launch(Context context, int type, int pageType) {
        context.startActivity(new Intent(context, AddWeChatPayOrAliPayActivity.class)
                .putExtra(C.EXTRA_PAYMENT, type)
                .putExtra(C.EXTRA_PAGE_TYPE, pageType));
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_add_we_chat_pay_or_ali_ay;
    }

    @Override
    protected void initActions() {
        mPaymentViewModel = ViewModelProviders.of(this).get(PaymentViewModel.class);

        int paymentType = getIntent().getIntExtra(C.EXTRA_PAYMENT, 0);
        mPageType = getIntent().getIntExtra(C.EXTRA_PAGE_TYPE, -1);
        switch (paymentType) {
            case C.VALUE_ALI_PAY:
                initAliPayView();
                loadAliPayInfo();
                break;
            case C.VALUE_WE_CHAT_PAY:
                initWeChatPayView();
                loadWeChatPayInfo();
                break;
        }

        // 选择付款码
        mSelectReceiptQrCodeLayout.setOnClickListener(v -> selectReceiptQrCode());
    }

    private void loadWeChatPayInfo() {
        if (mPageType == C.VALUE_MODIFY) {
            ((TextView) findViewById(R.id.title_text)).setText(R.string.modify_we_chat);
            mPaymentViewModel.weChatPayInfo().observe(this, payInfo -> {
//                mAddImageHintLayout.setVisibility(View.INVISIBLE);
                mNameEditText.setText(payInfo.getName());
                payAccountEdit.setText(payInfo.getWechat());
                //ImageViews.load(payInfo.getReceipt_code(), mReceiptQrCodeImage);
            });
        }
    }

    private void loadAliPayInfo() {
        if (mPageType == C.VALUE_MODIFY) {
            ((TextView) findViewById(R.id.title_text)).setText(R.string.modify_ali_pay);
            mPaymentViewModel.aliPayInfo().observe(this, aliPayInfo -> {
//                mAddImageHintLayout.setVisibility(View.INVISIBLE);
                mNameEditText.setText(aliPayInfo.getName());
                payAccountEdit.setText(aliPayInfo.getAlipay());
                //ImageViews.load(aliPayInfo.getReceipt_code(), mReceiptQrCodeImage);
            });
        }
    }

    private void initAliPayView() {
        ActivityBarHelper.init(this, R.string.title_add_alipay);
        paymentImage.setImageResource(R.drawable.ic_ali_payment);
        paymentText.setText(R.string.ali_pay);
        payAccountText.setText(R.string.ali_pay_account);
        payAccountEdit.setHint(R.string.please_input_ali_pay_account);

        mApplyButton.setOnClickListener(v -> startSubmitAliPay());
    }

    private void startSubmitAliPay() {
        if (mReceiptQrCodeUri == null) {
            Androids.makeText(R.string.please_add_rq_image);
            return;
        }

        String name = mNameEditText.getText().toString();
        if (TextUtils.isEmpty(name)){
            Androids.makeText(R.string.please_enter_your_real_name);
            return;
        }

        String payAccount = payAccountEdit.getText().toString();
        if (TextUtils.isEmpty(payAccount)){
            Androids.makeText(R.string.please_input_ali_pay_account);
            return;
        }

        SendVerificationCodeDialog.show(this, textView ->
                        sendMessage((TextView) textView, C.API_ALI_PAY_TYPE)
                , result -> submitAliPay(result.getCode()));
    }

    private void submitAliPay(String code) {
        String name = mNameEditText.getText().toString();
        String payAccount = payAccountEdit.getText().toString();
        mPaymentViewModel.setAliPayPayment(name, payAccount, Androids.toBase64(mReceiptQrCodeImage), code)
                .observe(this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        Androids.showProgressMessage(this, R.string.submission);
                    } else {
                        Androids.dismissProgressMessage();
                        Androids.makeText(resource.message);
                        if (resource.state == Resource.Status.SUCCESS) {
                            EventBus.getDefault().post(new SubmitAlipayEvent());
                            finish();
                        }
                    }
                });
    }

    private void sendMessage(TextView textView, int type) {
        mPaymentViewModel.sendMessage(type).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                textView.setClickable(false);
                textView.setBackgroundColor(Color.parseColor("#CCCCCC"));
                textView.setText(R.string.message_sending);
            } else {
                Androids.makeText(resource.message);
                if (resource.state == Resource.Status.SUCCESS) {
                    new TimeCount(textView).start();
                }
            }
        });
    }

    private void initWeChatPayView() {
        ActivityBarHelper.init(this, R.string.title_add_we_chat_pay);
        paymentImage.setImageResource(R.drawable.ic_we_chat_payment);
        paymentText.setText(R.string.we_chat_pay);
        payAccountText.setText(R.string.we_chat_account);
        payAccountEdit.setHint(R.string.please_input_we_chat_account);

        mApplyButton.setOnClickListener(v -> startSubmitWeChatPay());
    }

    private void startSubmitWeChatPay() {
        if (mReceiptQrCodeUri == null) {
            Androids.makeText(R.string.please_add_rq_image);
            return;
        }

        String name = mNameEditText.getText().toString();
        if (TextUtils.isEmpty(name)){
            Androids.makeText(R.string.please_enter_your_real_name);
            return;
        }

        String payAccount = payAccountEdit.getText().toString();
        if (TextUtils.isEmpty(payAccount)){
            Androids.makeText(R.string.please_input_we_chat_account);
            return;
        }

        SendVerificationCodeDialog.show(this, textView ->
                        sendMessage((TextView) textView, C.API_WE_CHAT_PAY_TYPE)
                , result -> submitWeChatPay(result.getCode()));
    }

    private void submitWeChatPay(String code) {
        String name = mNameEditText.getText().toString();
        String payAccount = payAccountEdit.getText().toString();
        mPaymentViewModel.setWeChatPayment(name, payAccount, Androids.toBase64(mReceiptQrCodeImage), code)
                .observe(this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        Androids.showProgressMessage(this, R.string.submission);
                    } else {
                        Androids.dismissProgressMessage();
                        Androids.makeText(resource.message);
                        if (resource.state == Resource.Status.SUCCESS) {
                            EventBus.getDefault().post(new SubmitWeChatPayEvent());
                            finish();
                        }
                    }
                });
    }

    private void selectReceiptQrCode() {
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, permissions)) {
            String rationale = getString(R.string.please_approve_camera_permissions);
            EasyPermissions.requestPermissions(this, rationale, 0, permissions);
        } else {
            selectReceiptQrCodeImage();
        }
    }

    private void selectReceiptQrCodeImage() {
        Matisse.from(this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .theme(R.style.Matisse_UNT)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(C.REQ_CHOOSE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        selectReceiptQrCodeImage();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.auto_authorization_failure)
                    .setRationale(R.string.please_manually_select_approve_camera_permissions).build().show();
        } else {
            Androids.makeText(R.string.authorization_failure);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            selectReceiptQrCodeImage();
        } else if (requestCode == C.REQ_CHOOSE && resultCode == RESULT_OK) {
            mReceiptQrCodeUri = Matisse.obtainResult(data).get(0);
            mReceiptQrCodeImage.setImageURI(mReceiptQrCodeUri);
            mAddImageHintLayout.setVisibility(View.INVISIBLE);
        }
    }
}
